<template>
  <div>
    <van-nav-bar title="头条-登录" />
    <van-form @submit="onSubmit">
      <van-field
        required
        v-model="user.mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          {
            required: true,
            message: '请填写正确手机号',
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
          }
        ]"
      />
      <van-field
        required
        v-model="user.code"
        type="password"
        name="code"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码', pattern: /^\d{6}$/ }]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="loading"
          loading-text="正在登陆中.."
          loading-type="spinner"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import { Notify } from 'vant'
import { setToken } from '@/utils/token.js'

export default {
  name: 'Login',
  data() {
    return {
      loading: false,
      user: {
        mobile: '18108068821',
        code: '246810' //246810
      }
    }
  },
  methods: {
    async onSubmit(values) {
      this.loading = true
      try {
        const { data: res } = await loginAPI(values)
        Notify({ type: 'success', message: '登录成功' })
        setToken(res.data.token)
        localStorage.setItem('refresh_token', res.data.refresh_token)
        this.$router.replace({
          path: this.$route.query.path || '/layout/home'
        })
      } catch (err) {
        Notify({ type: 'warning', message: '账户或密码错误' })
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped></style>
